<script setup lang="ts">
import type { LoginDto } from '@/apis/auth/type.d'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/apis/auth/index'
import { generateRouter } from '@/helper/router'
import { useAuthStore } from '@/store/modules/auth'
import { usePermissionStore } from '@/store/modules/permissions'

const permissionStore = usePermissionStore()
const authStore = useAuthStore()
const router = useRouter()
const loginFormRef = ref<InstanceType<typeof ElForm>>()
const loginForm = reactive<LoginDto>({
  username: 'zhouzhou',
  password: 'zhoupeng@0ABC',
})

// 密码
const rememberMe = ref(false)
const showPassword = ref(false)

// 加载状态
const isLoading = ref(false)
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度在 6 到 30 个字符', trigger: 'blur' },
  ],
}

// 处理登录
async function handleLogin() {
  // 表单验证
  const valid = await loginFormRef.value?.validate()
  if (!valid)
    return

  // 显示加载状态
  isLoading.value = true

  try {
    // 模拟登录请求
    const { data } = await login(loginForm)
    ElMessage.success('登录成功')
    authStore.setToken(data.accessToken)
    await permissionStore.getPermission()
    await generateRouter(router)

    const redirectPath = '/'
    router.push({ path: redirectPath, replace: true })

    // 记住密码
    if (rememberMe.value) {
      localStorage.setItem('rememberedUser', JSON.stringify({
        username: loginForm.username,
        password: loginForm.password,
      }))
    }
    else {
      localStorage.removeItem('rememberedUser')
    }
  }
  catch (error) {
    console.error('登录失败:', error)
    // ElMessage.error('登录失败，请检查用户名或密码')
  }
  finally {
    // 隐藏加载状态
    isLoading.value = false
  }
}

// 处理忘记密码
function handleForgotPassword() {
  ElMessageBox.alert(
    '请联系管理员重置密码',
    '忘记密码',
    {
      confirmButtonText: '确定',
    },
  )
}

onMounted(() => {
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    try {
      const user = JSON.parse(rememberedUser)
      loginForm.username = user.username || ''
      rememberMe.value = true
    }
    catch (e) {
      console.error('解析记住的用户信息失败:', e)
    }
  }
})
</script>

<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="login-bg" />

    <!-- 登录卡片 -->
    <div class="login-card">
      <div class="login-header">
        <h1 class="login-title">
          系统登录
        </h1>
        <p class="login-desc">
          请输入账号密码登录系统
        </p>
        <p class="login-desc">
          18382418960 -
          123456
        </p>
      </div>

      <ElForm
        ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" label-position="left"
        label-width="70px"
      >
        <!-- 用户名输入 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" :disabled="isLoading" />
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
            prefix-icon="Lock" :disabled="isLoading"
          >
            <template #suffix />
          </el-input>
        </el-form-item>

        <!-- 记住密码和忘记密码 -->
        <el-form-item class="form-actions">
          <ElSpace>
            <el-checkbox v-model="rememberMe" :disabled="isLoading">
              记住密码
            </el-checkbox>
            <el-link type="primary" :disabled="isLoading" @click="handleForgotPassword">
              忘记密码?
            </el-link>
          </ElSpace>
        </el-form-item>
      </ElForm>
      <el-button type="primary" style=" width: 100%;" :loading="isLoading" @click="handleLogin">
        登录
      </el-button>
    </div>

    <!-- 页脚 -->
    <footer class="login-footer">
      <p>©系统名称 zhouzhouee版权所有</p>
    </footer>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  position: relative;
  padding: 20px;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(circle at 50% 50%, rgba(147, 165, 184, 0.1) 0%, transparent 70%);
  z-index: 0;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 30px;
  z-index: 1;
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 8px;
}

.login-desc {
  color: #86909c;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.login-btn-group {
  margin-top: 20px;
}

.other-login {
  margin-top: 30px;
  text-align: center;
}

.other-login span {
  display: inline-block;
  color: #86909c;
  font-size: 14px;
  margin-bottom: 15px;
  position: relative;
}

.other-login span::before,
.other-login span::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 60px;
  height: 1px;
  background-color: #e5e6eb;
}

.other-login span::before {
  left: -70px;
}

.other-login span::after {
  right: -70px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-icon {
  font-size: 24px;
  color: #86909c;
  cursor: pointer;
  transition: all 0.2s ease;
}

.social-icon:hover {
  color: #165dff;
  transform: scale(1.1);
}

.login-footer {
  margin-top: 30px;
  color: #86909c;
  font-size: 12px;
  text-align: center;
  z-index: 1;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 20px;
  }

  .other-login span::before,
  .other-login span::after {
    width: 40px;
  }

  .other-login span::before {
    left: -50px;
  }

  .other-login span::after {
    right: -50px;
  }
}
</style>
